﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;

namespace Common
{
    public class TxtHelper
    {
        private static string logName = "/log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
        private static string LogTop = "/LogData";
        /// <summary>
        /// 创建文件夹
        /// </summary>
        public static void CreateLogFile()
        {
            
            string filePath = Directory.GetCurrentDirectory();
            DirectoryInfo dir = new DirectoryInfo(@filePath + LogTop);
            if (!dir.Exists)
            {
                Directory.CreateDirectory(@filePath + LogTop);
                if (Directory.Exists(@filePath + LogTop))
                {
                    Console.WriteLine("LogData创建成功");
                }
                dir.Create();
            }
            else
            {
                //Console.WriteLine("该目录已经存在");
            }
            if (!File.Exists(filePath + LogTop + logName))
            {
                try
                {
                    FileStream file = File.Create(filePath + LogTop + logName);
                    file.Dispose();
                    file.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        ///向日志文件中写入日志
        /// </summary>
        /// <param name="logText"></param>
        public static void LogWrite(string logText)
        {
            CreateLogFile();
            string filePath = Directory.GetCurrentDirectory() + LogTop + logName;
            StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8);
            try
            {
                sw.WriteLine("/********************************/");
                sw.WriteLine("日期：" + System.DateTime.Now.ToString());
                sw.WriteLine();
                sw.WriteLine(logText);
                sw.WriteLine("/********************************/");
                sw.WriteLine();
                sw.WriteLine();
                sw.Flush();
                sw.Dispose();
                sw.Close();
            }
            catch (Exception ex)
            {
                sw.Dispose();
                sw.Close();
            }
        }
    }
}
